package notice.service.impl;

import lombok.extern.slf4j.Slf4j;
import mq.util.MqUtil;
import notice.dto.OrderNoticeDto;
import notice.service.Observer;
import notice.service.Subject;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @description: 管理观察者
 * @author: zk
 * @since: 2022-08-17 10:23
 */
@Slf4j
@Component
public class DeductionNoticeManagement implements Subject, ApplicationContextAware {
    private final List<Observer> observers = new CopyOnWriteArrayList<>();

    @Resource
    private MqUtil mqUtil;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public void register(Observer observer) {
        if (!observers.contains(observer)) {
            observers.add(observer);
        }
    }

    @Override
    public void remove(Observer observer) {
        if (observers.contains(observer)) {
            observers.remove(observer);
        }
    }

    @Override
    public void notifyAllObservers(OrderNoticeDto notice) {
        Iterator<Observer> iterator = observers.iterator();
        while (iterator.hasNext()) {
            iterator.next().update(notice);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Observer> observerMap = applicationContext.getBeansOfType(Observer.class);
        if (!CollectionUtils.isEmpty(observerMap)) {
            observers.addAll(observerMap.values());
            log.info("扣款结果观察者注册成功！observers={}", observers);
        }
    }
}
